/*
 * table排序监听方法,返回参数column, prop, order
 * column: 列的数据
 * prop: 列名,恢复默认排序的时候返回null
 * order: 排序方式(ascending,descending,null)
 */
export function handleSortChange({ column, prop, order }) {
  // console.log('==============');
  // console.log(column, prop, order);
  this.order = { column: column, prop: prop, order: order };
  this.getData({ sortName: prop, sortOrder: order && (order === 'ascending' ? 'asc' : 'desc') });
}

/*
 * 翻页
 */
export function handleCurrentChange() {
  this.getData(this.order ? {
    sortName: this.order.prop,
    sortOrder: this.order.order && (this.order.order === 'ascending' ? 'asc' : 'desc')
  } : {});
}

export function handleSizeChange(val) {
  if (val === 10 || val === 20 || val === 50 || val === 100) {
    this.$store.getters.userInfo.pageSize = val;
  }
  this.pageSize = val;
  this.getData(this.order ? {
    sortName: this.order.prop,
    sortOrder: this.order.order && (this.order.order === 'ascending' ? 'asc' : 'desc')
  } : {});
}

/*
* table排序监听方法,返回参数column, prop, order
* column: 列的数据
* prop: 列名,恢复默认排序的时候返回null
* order: 排序方式(ascending,descending,null)
*/
export function columnCheck(index) {
  this.th[index].check = !this.th[index].check;
}

/*
 * 格式化时间
 * time:传入的时间,
 * cFormat: 生成的格式{y}-{m}-{d} {h}:{i}:{s}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null;
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
  let date;
  if (typeof time === 'object') {
    date = time;
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000;
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value];
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value;
    }
    return value || 0;
  })
  return time_str;
}

// 日期差判断
export function dateJudge(datestr) {
  let d1 = datestr.substr(0, 10);
  d1 = d1.replace(/-/g, '/');
  const c_date = new Date(d1);
  // console.log(c_date);
  let nd = new Date();
  nd = nd.valueOf();
  // console.log(nd);
  const date2 = Math.ceil((c_date - nd) / (24 * 60 * 60 * 1000));
  // console.log(c_date - nd);
  if (date2 === 0) {
    return '今天';
  } else if (date2 > 0 && date2 < 30) {
    return date2 + '天';
  } else if (date2 >= 30 && date2 < 360) {
    return Math.ceil(date2 / 30) + '月';
  } else if (date2 >= 360) {
    return Math.ceil(date2 / (30 * 12)) + '年';
  } else {
    const date3 = Math.ceil((nd - c_date) / (24 * 60 * 60 * 1000));
    return '逾期' + date3 + '天';
  }
}

